
var ImageResize = Class.create();

ImageResize.prototype = {
	container: null,
    initialize : function(item, options) {
		this.options = $H(options);
		this.item = $(item);
		this.resizing = 0;
		
		this.handle = this.item.select(".resize-handle")[0];

        if (this.options.get('scale')) {
        	this.scale = this.options.get('scale');
        } else {
        	this.scale = 0;
        }
        
		if (this.options.get('onResize')) {
			this.onResizeEvent = this.options.get('onResize');
		} else {
			this.onResizeEvent = function(){};
		}
		
		if (this.options.get('container')) {
			this.container = $(this.options.get('container'));
		}
		
		this.item.select('.resize-handle-lt').each(function(el){
			el.observe('mousedown', this.onStart.bind(this, 
					{'t':1,'r':0,'b':0,'l':1}));
		}.bind(this));
		this.item.select('.resize-handle-lb').each(function(el){
			el.observe('mousedown', this.onStart.bind(this, 
					{'t':0,'r':0,'b':1,'l':1}));
		}.bind(this));
		this.item.select('.resize-handle-rt').each(function(el){
			el.observe('mousedown', this.onStart.bind(this, 
					{'t':1,'r':1,'b':0,'l':0}));
		}.bind(this));
		this.item.select('.resize-handle-rb').each(function(el){
			el.observe('mousedown', this.onStart.bind(this, 
					{'t':0,'r':1,'b':1,'l':0}));
		}.bind(this));
		this.item.select('.resize-handle-dl-t').each(function(el){
			el.observe('mousedown', this.onStart.bind(this, 
					{'t':1,'r':0,'b':0,'l':0}));
		}.bind(this));
		this.item.select('.resize-handle-dl-l').each(function(el){
			el.observe('mousedown', this.onStart.bind(this, 
					{'t':0,'r':0,'b':0,'l':1}));
		}.bind(this));
		this.item.select('.resize-handle-dl-r').each(function(el){
			el.observe('mousedown', this.onStart.bind(this, 
					{'t':0,'r':1,'b':0,'l':0}));
		}.bind(this));
		this.item.select('.resize-handle-dl-b').each(function(el){
			el.observe('mousedown', this.onStart.bind(this, 
					{'t':0,'r':0,'b':1,'l':0}));
		}.bind(this));
    },
    resize: function (x, y, rx, ry) {
        
        if (this.scale) {
        	//console.log("Resize XY : " + x + ", " + y);
        	if (x != 0) {
        		y = x / this.scale;
        	} else {
        		x = y * this.scale;
        	}
        	//console.log("Scale " + this.scale + " : " + x + ", " + y);
        }
        
    	var width = this.dim.width + x;
    	var height = this.dim.height + y;
    	
    	if (width < 1) {
    		width = 1;
    	}
    	if (height < 1) {
    		height = 1;
    	}
    	    	
    	if (this.pos) {
    		var styles = {};
        	var left = this.pos.left;
        	var top = this.pos.top;
        	if (rx) { 
            	left = (this.pos.left - width + this.dim.width);
        	}
        	if (ry) {
            	top = (this.pos.top - height + this.dim.height);
        	}
        	
        	if (this.clip) {
	        	if (left < 0) {
	        		width += left;
	        		left = 0;
	        		if (this.scale) {
	        			return;
	        		}
	        	}
	        	if (top < 0) {
	        		height += top;
	        		top = 0;
	        		if (this.scale) {
	        			return;
	        		}
	        	}
	        	if (top + height > this.clip.height) {
	        		height = this.clip.height - top;
	        		if (this.scale) {
		        		return;
	        		}
	        	}
	        	if (left + width > this.clip.width) {
	        		width = this.clip.width - left;
	        		if (this.scale) {
	        			return;
	        		}
	        	}
        	}

        	styles.left = '' + left + 'px';
        	styles.top = '' + top + 'px';
        	
        	this.item.setStyle(styles);
        	this.onResizeEvent(width, height, top, left);
    	} else {
    		this.onResizeEvent(width, height);
    	}

    	var styles = {width: ''+width + 'px', height: ''+ height + 'px'};
    	this.handle.setStyle(styles);
    },
    onResize: function(e) {
    	if (this.arrow.l && this.arrow.t) {
            this.resize(this.clientX - e.clientX, this.clientY - e.clientY, 1, 1);
        } else
        if (this.arrow.r && this.arrow.t) {
			this.resize(e.clientX - this.clientX, this.clientY - e.clientY, 0, 1);
		} else
		if (this.arrow.l && this.arrow.b) {
			this.resize(this.clientX - e.clientX, e.clientY - this.clientY, 1, 0);
		} else
		if (this.arrow.r && this.arrow.b) {
			this.resize(e.clientX - this.clientX, e.clientY - this.clientY, 0, 0);
		} else
        if (this.arrow.l) {
            this.resize(this.clientX - e.clientX, 0, 1, 0);
        } else
        if (this.arrow.r) {
            this.resize(e.clientX - this.clientX, 0, 0, 0);
        } else
 		if (this.arrow.t) {
            this.resize(0, this.clientY - e.clientY, 0, 1);
 		} else
        if (this.arrow.b) {
            this.resize(0, e.clientY - this.clientY, 0, 0);
        }
    },
    onStop: function() {
        //console.log("Stop resizing");
        this.resizing = 0;
        try {
        	Event.stopObserving(document, 'mousemove');
        } catch (e) {
        }
        try {
        	Event.stopObserving(document, 'mouseup');
        } catch (e) {
        }
        try {
        	Event.stopObserving(document, 'blur');
        } catch (e) {
        }
    },
    onStart: function(r, e) {
        // console.debug(r);
        this.arrow = r;
        
        if (this.resizing) {
            return;
        }
        
        this.resizing = 1;

		this.clientX = e.clientX;
		this.clientY = e.clientY;
		this.dim = this.handle.getDimensions();
		
		if (this.container) {
			if (this.item.getStyle('position') != 'absolute') {
				console.error("!!POSITION NOT VALID!!");
			} else {
				this.pos = this.item.positionedOffset();
				this.clip = this.container.getDimensions();
			}
		} else if (this.item.getStyle('position') == 'absolute') {
			this.pos = this.item.positionedOffset();
			this.clip = null;
		}
		
        Event.stop(e);
        
        Event.observe(document, 'mousemove', this.onResize.bind(this));
        Event.observe(document, 'mouseup', this.onStop.bind(this));
        Event.observe(window, 'blur', this.onStop.bind(this));
        
    }
}

var ImageMoveable = Class.create();

ImageMoveable.prototype = {
    initialize : function(item, options) {
		this.options = $H(options);
		this.item = $(item);
		this.moving = 0;
		
		if (this.options.get('handle')) {
			this.handle = $(this.options.get('handle'));
		} else {
			this.handle = this.item;
		}
		this.item.setStyle({position:'absolute'});
		
		if (this.options.get('left')) {
			this.item.setStyle({left: '' + this.options.get('left') + 'px'});
		}
		if (this.options.get('top')) {
			this.item.setStyle({top: '' + this.options.get('top') + 'px'});
		}
		if (this.options.get('container')) {
			this.container = $(this.options.get('container'));
		}

		if (this.options.get('onMove')) {
			this.onMoveEvent = this.options.get('onMove');
		} else {
			this.onMoveEvent = function(){};
		}

		this.handle.observe('mousedown', this.onMouseDown.bind(this));
    },
    onMouseDown: function (e) {
        var el = Event.element(e);
        var el = Event.findElement(e, '.move-handle');
        
        if (!el.hasClassName('move-handle')) {
            return;
        }
        
        if (this.moving) {
            return;
        }
        
        this.moving = 1;

		this.clientX = e.clientX;
		this.clientY = e.clientY;
		
		this.pos = this.item.positionedOffset();

		if (this.container) {
			this.dim = this.container.getDimensions();
    	}
    	
        Event.stop(e);
        
        Event.observe(document, 'mousemove', this.onMove.bind(this));
        Event.observe(document, 'mouseup', this.onStop.bind(this));
        Event.observe(window, 'blur', this.onStop.bind(this));

        //console.log("Start moving");
        
    },
    onStop: function() {
        //console.log("Stop Moving");
        this.moving = 0;
        try {
        	Event.stopObserving(document, 'mousemove');
        } catch (e) {
        }
        try {
        	Event.stopObserving(document, 'mouseup');
        } catch (e) {
        }
        try {
        	Event.stopObserving(document, 'blur');
        } catch (e) {
        }
    },
    onMove: function(e) {
        var top = this.pos.top + e.clientY - this.clientY;
        var left = this.pos.left + e.clientX - this.clientX;
		var dim = this.item.getDimensions();
		
        if (this.dim) {
            if (top < 0) {
                top = 0;
            } else if (top + dim.height > this.dim.height) {
                top = this.dim.height - dim.height;
            }
            if (left < 0) {
            	left = 0;
            } else if (left + dim.width > this.dim.width) {
            	left = this.dim.width - dim.width;
            }
        }

        /*
		console.log("Move: " 
				+ top + ',' + left + '  '
				+ dim.width + ',' + dim.height + '  '
				+ this.dim.width + ',' + this.dim.height
			)
        */
        
        this.item.setStyle({left: '' + left + 'px', top: '' + top + 'px'});
			
        this.onMoveEvent(top, left);
    }
};

var ImageClipBoard = Class.create();

ImageClipBoard.prototype = {
    initialize : function(item, options) {
    	this.item = $(item);
		this.options = $H(options);
		
		this.item.select('.resize-able').each(function (el){
			new ImageResize(el, {
				container: this.item,
				scale: this.options.get('scale'),
				onResize: this.onClipResize.bind(this)
			});
		}.bind(this));
		this.item.select('.move-able').each(function (el){
			new ImageMoveable(el, {
				handle: el.select('.move-handle')[0],
				container: this.item,
				onMove: this.onClipMove.bind(this) 
			});
		}.bind(this));
		
		if (this.options.get('reset')) {
			var ob = $(this.options.get('reset'));
			ob.observe('click', this.onReset.bind(this));
		}
		if (this.options.get('apply')) {
			var ob = $(this.options.get('apply'));
			ob.observe('click', this.onApply.bind(this));
		}
	},
	onClipResize: function(width, height, top, left) {
		// console.log("Resize: " + top + ',' + left + ',' + width + ',' + height);
		$(this.item.id + '_mask_image').setStyle(
				{top: '-'+top+'px', left: '-'+left+'px'});
	},
	onClipMove: function(top, left) {
		// console.log("Move: " + top + ',' + left);
		$(this.item.id + '_mask_image').setStyle(
				{top: '-'+top+'px', left: '-'+left+'px'});
	},
	onReset: function() {
		$(this.item.id + '_mask').setStyle({top: '0px', left: '0px'});
		$(this.item.id + '_mask_image').setStyle({top: '0px', left: '0px'});
		this.item.select('.resize_image').each(function (el){
			el.setStyle({
				width: '' + this.options.get('width') + 'px',
				height: '' + this.options.get('height') + 'px' 
			});
		}.bind(this));
		return false;
	},
	onApply: function() {
		var bd = $(this.item.id + '_original').getDimensions();
		var md = $(this.item.id + '_mask').getDimensions();
		var mp = $(this.item.id + '_mask').positionedOffset();

		var rect = {
				bw: bd.width,
				bh: bd.height,
				mw: md.width,
				mh: md.height,
				ml: mp.left,
				mt: mp.top,
				file: this.options.get('current_file')
			};
		
		var queryString = $H(rect).toQueryString();

		//console.debug(rect);
		window.open(this.options.get('apply_action') + "?" + queryString, "_self");
	}
};
